package com.sailfish.springbootdemo.controller.db2;

import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db1.PcbaCompany;
import com.sailfish.springbootdemo.pojo.db1.PcbaLine;
import com.sailfish.springbootdemo.pojo.db2.*;
import com.sailfish.springbootdemo.pojo.db4.ApproveH3c;
import com.sailfish.springbootdemo.service.db2.*;
import com.sailfish.springbootdemo.service.db4.ApproveH3cService;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.ResultUtil;
import com.sailfish.springbootdemo.utils.SfsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/thirdApiSend2")
public class ThirdApiSend2Controller {
    @Autowired
    private CapacityMatchService capacityMatchService;
    @Autowired
    private PcbParentFactoryInfoService pcbParentFactoryInfoService;
    @Autowired
    private  PcbSonFactoryInfoService pcbSonFactoryInfoService;
    @Autowired
    private PcbSpecialProcessService pcbSpecialProcessService;
    @Autowired
    private ThirdApiService thirdApiService;
    @Autowired
    private PcbMaterialService pcbMaterialService;
    @Autowired
    SfsUtils sfsUtils;

    @Value("${personal.config.apis.sign}")
    private String sign;
    @Value("${personal.config.email.templateId}")
    private String templateCode;

    @PostMapping("/getAllCapacityInfo")
    public Result getData() {
        List<FactoryInfoVM> allCapacityInfo = capacityMatchService.getAllCapacityInfo();
        return ResultUtil.success(allCapacityInfo);
    }

    @PostMapping("/getAllFactory")
    public Result getAllFactory(String signature) {
        try {
            if (signature == null || "".equals(signature)) {
                return ResultUtil.error(500, "缺少参数signature", "Miss Param signature", null);
            }
            String md5Sign = CommonUtils.encryptToMD5(CommonUtils.encryptToMD5(sign));
            if (!signature.equals(md5Sign)) {
                return ResultUtil.error(500, "签名不正确", "Error Signature", null);
            }
            List<PcbParentFactoryInfo> children = pcbParentFactoryInfoService.getAll(null, null, null, null, null, null, null, null, null, null, null, null, 1, null);
            return ResultUtil.success(children);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }


    @PostMapping("/getMatchParamList")
    public Result getMatchParam() {
        List<PcbSizeParam> matchParam = capacityMatchService.getMatchParam(1);
        return ResultUtil.success(matchParam);
    }

    @PostMapping("/getMatchParamByKey")
    public Result getMatchParamByKey(String key) {
        PcbSizeParam matchParam = capacityMatchService.getMatchParamByKey(key);
        return ResultUtil.success(matchParam);
    }

    //type: surfaceType,getAllFactory,materialLibrary
    @PostMapping("/getSpecialParam")
    public Result getSpecialParam(String type,Integer id) {
        if (type == null) {
            return ResultUtil.error(500, "参数type为空", "param type is null", null);
        }
        if (type.equals("surfaceType")) {
            PcbSizeParam matchParam = capacityMatchService.getMatchParamByName("表面处理方式");
            if (matchParam != null) {
                String paramOptions = matchParam.getParamOptions();
                if (!StringUtils.isBlank(paramOptions)) {
                    String[] split = paramOptions.split(",");
                    return ResultUtil.success(split);
                }
            }
            return ResultUtil.success(null);
        }
        if (type.equals("getAllFactory")) {
            List<PcbParentFactoryInfo> children = pcbParentFactoryInfoService.getAll(null, null, null, null, null, null, null, null, null, null, null, null, 1, null);
            return ResultUtil.success(children);
        }
        if (type.equals("materialLibrary")) {
            List<PcbMaterialLibrary> materialList = pcbMaterialService.getMaterialList();
            return ResultUtil.success(materialList);
        }
        if(type.equals("son")){
            if(id == null){
                return ResultUtil.error(500, "参数id为空", "param id is null", null);
            }
             PcbSonFactoryInfo byId = pcbSonFactoryInfoService.getById(id);
            List<PcbSonFactoryInfo> list = new ArrayList<>();
            if(byId != null){
                list.add(byId);
            }
            return ResultUtil.success(list);
        }

        if(type.equals("specialProcess")){
            List<PcbSpecialProcessInfo> allData = pcbSpecialProcessService.getAllByLimit(null, null, "", 1);
            return ResultUtil.success(allData);
        }
        return ResultUtil.success(null);
    }

    @PostMapping("/getAllPcbSpecialProcess")//, Integer page,Integer pageSize
    public Result getAllPcbSpecialProcess(String pcbSpecialProcessName, String pcbSpecialProcessNameEn, String version) {
        List<PcbSpecialProcessInfo> allData = pcbSpecialProcessService.getAllByLimit(pcbSpecialProcessName, pcbSpecialProcessNameEn, version, 1);
        return ResultUtil.success(allData);
    }

    @PostMapping("/sendMail")
    public Result sendMail(@RequestBody String data) throws Exception {
        final JSONObject jsonObject = JSONObject.parseObject(data);
        String mailContentTitle = jsonObject.getString("mailContentTitle");
        String mailContent = jsonObject.getString("mailContent");
        String mailAddress = jsonObject.getString("mailAddress");
        String title = mailContentTitle;   //邮件主题
        if (StringUtils.isBlank(mailAddress)) {
            return ResultUtil.error(500, "参数mailAddress为空", "param mailAddress is null", null);
        }

        List<MailAddress> mailAddressList = new ArrayList<MailAddress>();//收件列表
        final String[] split = mailAddress.split(";");
        for (int i = 0; i < split.length; i++) {
            if (!StringUtils.isBlank(split[i])) {
                MailAddress mailAddress1 = new MailAddress();
                mailAddress1.setMailAddress(split[i]);
                mailAddress1.setType(0);
                mailAddressList.add(mailAddress1);
            }
        }

        List<MailAdGroup> mailAdGroupList = new ArrayList<>();//域群组收件列表
        List<MailDepartment> mailDepartmentList = new ArrayList<>();//部门编码收件列表
        List<MailGroupParam> mailGroupParamList = new ArrayList<>();//自定义接收数组收件列表
        Integer priority = 1;   //优先级，1普通，2有限
        String sendMail = "";    //发件箱（必须为公共邮箱，并向管理员申请开通自定义发件箱发送能力），如果不填，则使用系统默认发件箱(AppEos@h3c.com)
        String username = "";
        Result result = thirdApiService.sendMail(username, title, mailContentTitle, mailContent, templateCode, mailAddressList, null, mailAdGroupList, mailDepartmentList, mailGroupParamList, priority, sendMail);
        return result;
    }


    @PostMapping("/test")
    public Result test(HttpServletRequest req, String secretKey) throws Exception {
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
        MultipartFile file = mRequest.getFile("file");
        sfsUtils.upload(file, secretKey);
        return ResultUtil.success(null);
    }
    @PostMapping("/test2")
    public Result test()  {
        try{
            Thread.sleep(1000*61);
            return ResultUtil.success(null);
        }
        catch (Exception e){
            return ResultUtil.error(500,e.getMessage(),e.getMessage(),null);
        }
    }

    @PostMapping("/preview")
    public Result preview(String fileSid, String secretKey) throws Exception {
        SfsUtils.SfsFileData preview = sfsUtils.preview(secretKey, fileSid);
        return ResultUtil.success(preview);
    }

    @Autowired
    ApproveH3cService approveH3cService;

    @PostMapping("/insertOrUpdateApproveH3c")
    public Result insertOrUpdate(@RequestBody String data) {
        Result result = approveH3cService.insertOrUpdate(data);
        return result;
    }
    @PostMapping("/updateStatus")
    public Result update(@RequestBody String data) {
        Result result = approveH3cService.updateData(data);
        return result;
    }

    @PostMapping("/getApproveList")
    public Result getApproveList(@RequestBody String data) {
        JSONObject jsonObject = approveH3cService.getApproveList(data);
        return ResultUtil.success(jsonObject);
    }

    @PostMapping("/updateData")
    Result updateData(@RequestBody String data) {//String systemId, String workFlowId, String docId, String currentNodeId, String empNumber,String buttonType, String targetReceiver, String opinion, String data
        Result result = approveH3cService.updateData(data);
        return result;
    }

    @PostMapping("/getById")
    public Result getById(String systemid, String processid, String docunid)
    {
        ApproveH3c approveH3c = approveH3cService.getById(systemid, processid, docunid);
        return ResultUtil.success(approveH3c);
    }
}
